﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace LockTime
{
    /// <summary>
    /// SYSTEMTIME系统时间结构体
    /// </summary>
    public struct SYSTEMTIME
    {
        public ushort wYear;
        public ushort wMonth;
        public ushort wDayOfWeek;
        public ushort wDay;
        public ushort wHour;
        public ushort wMinute;
        public ushort wSecond;
        public ushort wMilliseconds;
    }
    /// <summary>
    /// 进行时间格式的转换
    /// </summary>
    public class SystemTime
    {
        [DllImport("Kernel32.dll", CharSet = CharSet.Ansi)]
        public static extern bool SetLocalTime(ref SYSTEMTIME Time);
        [DllImport("Kernel32.dll")]
        public static extern void GetLocalTime(ref SYSTEMTIME Time);
        [DllImport("Kernel32.dll")]
        public static extern bool SetSystemTime(ref SYSTEMTIME Time);
        [DllImport("Kernel32.dll")]
        public static extern void GetSystemTime(ref SYSTEMTIME Time);
        
        /// <summary>
        /// 由DateTime转换为SYSTEMTIME
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static SYSTEMTIME FromDateTime(DateTime time)
        {
            SYSTEMTIME tmp = new SYSTEMTIME();
            tmp.wYear = (ushort)time.Year;
            tmp.wMonth = (ushort)time.Month;
            tmp.wDayOfWeek = (ushort)time.DayOfWeek;
            tmp.wDay = (ushort)time.Day;
            tmp.wHour = (ushort)time.Hour;
            tmp.wMinute = (ushort)time.Minute;
            tmp.wSecond = (ushort)time.Second;
            tmp.wMilliseconds = (ushort)time.Millisecond;
            return tmp;
        }
        /// <summary>
        /// 由SystemTime转换为DateTime
        /// </summary>
        /// <returns></returns>
        public static DateTime ToDateTime(SYSTEMTIME systemtime)
        {
            return new DateTime(systemtime.wYear, systemtime.wMonth, systemtime.wDay, systemtime.wHour, systemtime.wMinute, systemtime.wSecond, systemtime.wMilliseconds);
        }
        public static DateTime GetNetDateTime()
        {
            WebRequest request = null;
            WebResponse response = null;
            WebHeaderCollection headerCollection = null;
            string datetime = string.Empty;
            try
            {
                //联网获取时间，其实就是获取网页上的时间而已，并没有去联什么时间服务器
                request = WebRequest.Create("http://www.baidu.com");
                request.Timeout = 3000;
                request.Credentials = CredentialCache.DefaultCredentials;
                response = (WebResponse)request.GetResponse();
                headerCollection = response.Headers;
                foreach (var h in headerCollection.AllKeys)
                {
                    if (h == "Date")
                    {
                        datetime = headerCollection[h];
                    }
                }
                
            }
            catch (Exception)
            {
                datetime = "error";
            }
            finally
            {
                //清理工作
                if (request != null)
                {
                    request.Abort();
                }
                if (response != null)
                {
                    response.Close();
                }
                if (headerCollection != null)
                {
                    headerCollection.Clear();
                }
            }
            if (datetime == "error")
                throw new Exception("获得网络时间失败");
            return Convert.ToDateTime(datetime);
        }
    }
}
